package com.example.personalcenter.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.personalcenter.DetailActivity;
import com.example.personalcenter.adapter.MyListAdapter;
import com.example.personalcenter.databinding.FragmentHomeBinding;
import com.example.personalcenter.model.MyItem;
import com.example.personalcenter.model.UserViewModel;

public class HomeFragment extends Fragment {

    private FragmentHomeBinding binding;
    private UserViewModel vm;
    private MyListAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        vm = new ViewModelProvider(requireActivity()).get(UserViewModel.class);
        adapter = new MyListAdapter();
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerView.setAdapter(adapter);

        // 下拉刷新
        binding.btnRefresh.setOnClickListener(v -> vm.loadItems());

        // 点击跳转详情
        adapter.setOnItemClickListener(item -> {
            Intent intent = new Intent(getContext(), DetailActivity.class);
            intent.putExtra("title", item.getTitle());
            intent.putExtra("desc", item.getDesc());
            startActivity(intent);
        });

        // 长按删除
        adapter.setOnItemLongClickListener(item -> {
            vm.deleteItem(item);
            return true;
        });

        // 数据观察
        vm.getItems().observe(getViewLifecycleOwner(), items -> {
            adapter.setData(items);

        });

        // 首次加载
        if (vm.getItems().getValue() == null || vm.getItems().getValue().isEmpty())
            vm.loadItems();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}